package com.jblv.frame.common.utils.jwt;

import com.jblv.frame.common.utils.jwt.jackjson.JsonParser;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;

import com.jblv.frame.common.utils.jwt.jackjson.JsonParserFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.MacSigner;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.jwt.crypto.sign.SignatureVerifier;
import org.springframework.security.jwt.crypto.sign.Signer;
/**
 * @author happyonion.yangtao
 * @version 1.0
 * @title JwtUtils
 * @projectName jblv-frame
 * @packageName com.jblv.common.utils
 * @description JwtUtils
 * @date Create at 2020/4/30 23:12
 * @since jdk1.8
 */
public class JwtUtils {
    private static JsonParser objectMapper = JsonParserFactory.create();
    private static String verifierKey = (new RandomValueStringGenerator()).generate();
    private static Signer signer;
    private static SignatureVerifier verifier;

    public JwtUtils() {
    }

    public static String enhance(Map<String, Object> params) {
        String content;
        try {
            content = objectMapper.formatMap(params);
        } catch (Exception var3) {
            throw new IllegalStateException("Cannot convert access token to JSON", var3);
        }

        String token = JwtHelper.encode(content, signer).getEncoded();
        return token;
    }

    public static Map<String, Object> decode(String token) throws Exception {
        try {
            Jwt jwt = JwtHelper.decodeAndVerify(token, verifier);
            String content = jwt.getClaims();
            Map<String, Object> map = objectMapper.parseMap(content);
            return map;
        } catch (Exception var4) {
            throw new Exception("Cannot convert access token to JSON", var4);
        }
    }

    static {
        signer = new MacSigner(verifierKey);
        verifier = null;
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jblv-frame.jks"), "jblv-frame".toCharArray());
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("jblv-frame");
        PrivateKey privateKey = keyPair.getPrivate();
        signer = new RsaSigner((RSAPrivateKey)privateKey);
        RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
        verifier = new RsaVerifier(publicKey);
        verifierKey = "-----BEGIN PUBLIC KEY-----\n" + new String(Base64.encode(publicKey.getEncoded())) + "\n-----END PUBLIC KEY-----";
    }
}
